﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(Rigidbody))]
public class FloaterByPhysics : MonoBehaviour {
	public float waterLevel;
    public float floatHeight = 1f;
    public float bounceDamp = 0.5f;
    public Vector3 buoyancyCentreOffset;

    Transform _transform;
    Rigidbody _rigidbody;

    void Start() {
        _transform = GetComponent<Transform>();
        _rigidbody = GetComponent<Rigidbody>();
    }

    void FixedUpdate () {
        if (floatHeight <= 0f) {
            floatHeight = 1f;
        }

        var actionPoint = _transform.position + _transform.TransformDirection(buoyancyCentreOffset);
        var forceFactor = 1f - ((actionPoint.y - waterLevel) / floatHeight);

        if (forceFactor > 0f) {
            var uplift = -Physics.gravity * (forceFactor - _rigidbody.velocity.y * bounceDamp);
            _rigidbody.AddForceAtPosition(uplift, actionPoint);
        }
    }
}
